package cn.sz.hy.logic.strategy.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jxl.Cell;
import jxl.LabelCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import cn.sz.hy.common.EventBus;
import cn.sz.hy.common.Globel;
import cn.sz.hy.logic.strategy.ExecuteStrategy;
import cn.sz.hy.logic.strategy.vo.SheetItem;
import cn.sz.hy.logic.strategy.vo.TableVo;

public abstract class XlsStrategy implements ExecuteStrategy {
	private List<Workbook> workBookList = new ArrayList<Workbook>();
	protected static EventBus eBus = EventBus.getInstance();
	protected TableVo main;
	protected TableVo backup;
	protected TableVo det;

	public XlsStrategy() {
		super();
	}

	public Workbook getWorkbook(String path) {
		File file = new File(path);
		if (file.exists()) {
			try {
				Workbook wb = Workbook.getWorkbook(file);
				workBookList.add(wb);
				return wb;
			} catch (BiffException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 获得表头
	 * 
	 * @param path
	 * @return
	 */
	public List<TableVo> loadHeader(String path) {
		List<TableVo> sheetList = new ArrayList<TableVo>();
		Workbook workbook = getWorkbook(path);
		if (workbook == null) {
			return null;
		}
		Sheet[] sheets = workbook.getSheets();
		for (Sheet sheet : sheets) {
			int rowCount = sheet.getRows();
			if (rowCount == 0) {
				continue;
			}

			TableVo se = new TableVo(null, sheet, sheet.getName());
			getSheetItem(sheet, se, false);

			sheetList.add(se);
		}
		return sheetList;
	}

	public void getSheetItem(Sheet sheet, TableVo vo, boolean notFrist) {
		if(notFrist){
			vo.row = vo.row + 1;
		}
		Cell[] header = sheet.getRow(vo.row);
		
		List<SheetItem> items = new ArrayList<SheetItem>();
		for (Cell cell : header) {
			items.add(new SheetItem(cell.getContents(), cell.getColumn()));
		}
		vo.setColumns(items);
	}

//	private boolean isHeader(Cell[] headerCells) {
//		boolean isHeader = true;
//		for (Cell headerCell : headerCells) {
//			isHeader = isHeader && (headerCell instanceof LabelCell);
//		}
//		return isHeader;
//	}

	public void close() {
		Iterator<Workbook> itr = workBookList.iterator();
		while (itr.hasNext()) {
			Workbook wb = itr.next();
			wb.close();
			itr.remove();
		}
	}

}
